package ter.find.pattern.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.JTableHeader;
import ter.find.pattern.BaseTableModel;
import ter.find.pattern.ModelCharge;
import ter.find.pattern.ModelMotif;
import ter.find.pattern.MotifTableModel;
import ter.find.pattern.ReadWriteFile;
import ter.find.pattern.algoFind.RunSearch;

public class FindPanel extends JPanel {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JSpinner spinSupport=new JSpinner();
	private JSlider sliderSupport=new JSlider();
	private JLabel labeltext=new JLabel("Support");
	private JPanel dispMotif=new JPanel();
	private JPanel dispDataSeq=new JPanel();
	private JPanel topPan=new JPanel();
	private JPanel panelSup=new JPanel();
	private JPanel panelSupRight=new JPanel();
	JPanel panToolsBar=new JPanel();
	
	private JLabel label1=new JLabel("Nombre de séquence: ");
	private JLabel label2=new JLabel("Variation Temperature: ");
	private JLabel value1=new JLabel("0");
	private JLabel value2=new JLabel("-");
	
	ModelMotif m;
	JButton b=new JButton("bout");
	ControlPanel control;
	int support;
	
	/*Boutons*/
	JButton bCharger;
	JButton bsave;
	JButton bChanger=new JButton("Changer");
	public JButton bFind;
	JScrollPane scrolTable=new JScrollPane();
	
	
	JTable table=new JTable();
	JTable table1=new JTable();
	//JScrollPane scrollPane = new JScrollPane(table);
	JScrollPane scrollPane1 = new JScrollPane(table);
	private SlideContainer slideContainer = new SlideContainer(1000,200);
	private SlideContainer slideContainer2 = new SlideContainer(1000,200);
	JFileChooser fileChose=new JFileChooser();
	public String path;
	public String datasave=null;
	
	FindPanel(){
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		//fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		bsave=new JButton("Enregistrer");
		fileChose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		bCharger=new JButton("Charger");
		bFind=new JButton("Rechercher");
		bFind.setEnabled(false);
		bsave.setEnabled(false);
		bChanger.setEnabled(false);
		paramTable(table, 800, 70);
		paramTable(table1, 800, 70);
        
        panelSupRight.setLayout(new GridLayout(2, 2));
		panelSupRight.add(label1);
		panelSupRight.add(value1);
		panelSupRight.add(label2);
		panelSupRight.add(value2);

        panelSup.setLayout(new FlowLayout(FlowLayout.LEFT));
		panelSup.setBorder(new TitledBorder("Définir Support"));
		panelSup.add(labeltext);

		spinSupport.setPreferredSize(new Dimension(50, 20));
		panelSup.add(spinSupport);
		
		
		sliderSupport.setMajorTickSpacing(20);
		sliderSupport.setMinorTickSpacing(5);
		sliderSupport.setPaintTicks(true);
		sliderSupport.setPaintLabels(true);
		panelSup.add(sliderSupport);
		panelSup.add(panelSupRight);
		
		dispMotif.setBorder(new TitledBorder("Séquence Base"));
		dispMotif.add(slideContainer2);
		
		topPan.setLayout(new BoxLayout(topPan, BoxLayout.Y_AXIS));
	    topPan.add(panelSup);  
	    topPan.add(dispMotif);
	    
	    //dispDataSeq.setLayout(new BoxLayout(dispDataSeq, BoxLayout.X_AXIS));
		dispDataSeq.setBorder(new TitledBorder("Motif"));
		dispDataSeq.add(slideContainer);
		
		

		panToolsBar.setBorder(new TitledBorder("Control"));
		panToolsBar.add(bCharger);
		panToolsBar.add(bsave);
		//panToolsBar.add(bChanger);
		panToolsBar.add(bFind);
		
		
		
		label1.setBackground(Color.blue);
		
		
		/*Ajout du tableau de model de motif dans le panneu GUI*/
		this.add(topPan,BorderLayout.NORTH);  
		this.add(dispDataSeq,BorderLayout.CENTER);
		this.add(panToolsBar,BorderLayout.SOUTH);

		sliderSupport.addChangeListener(new MyChangeListener());
		spinSupport.addChangeListener(new MyChangeListener());
		bFind.addActionListener(new MotifActionListener());
		bCharger.addActionListener(new LoadActionListener());
		bsave.addActionListener(new SaveActionListener());
	}
	
	
	
	public void paramTable(JTable tab,int width,int height){
		tab.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
    	tab.setPreferredScrollableViewportSize(new Dimension(width, height));
        tab.setFillsViewportHeight(true);
        tab.setCellSelectionEnabled(true);
	}
	
	public void addSSListener(ChangeListener act){
		sliderSupport.addChangeListener(act);
		spinSupport.addChangeListener(act);
	}
	
	
	public class MyChangeListener implements ChangeListener{

		@Override
		public void stateChanged(ChangeEvent act) {
			// TODO Auto-generated method stub
			Object source = act.getSource();
		     if (source instanceof JSlider) {
		    	 spinSupport.setValue(sliderSupport.getValue());
		         //dispDataSeq.setBackground(Color.red);
		    }else if(source instanceof JSpinner){
		    	sliderSupport.setValue((Integer)spinSupport.getValue());
		    	
		    }
		}
		
	}
	
	public class MotifActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			Object selec = e.getSource();
			if(selec.equals(bFind)){
				System.out.println(BasePanel.getListIdseq());
				RunSearch r=new RunSearch();
	        	support=sliderSupport.getValue();
	        	MotifTableModel model = new MotifTableModel(r.start(support,path,BasePanel.getListIdseq()));
	        	datasave=model.saveData();
	        	MotifPanel mpan=new MotifPanel(model);
	        	slideContainer.add(mpan);
	        	dispDataSeq.updateUI();

			}
		}
		
	}
	
	
	public class LoadActionListener implements ActionListener{

		
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			Object selec = e.getSource();
			if(selec.equals(bCharger)){
				RunSearch r=new RunSearch();
				int returnVal = fileChose.showOpenDialog(FindPanel.this);

				if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File file = fileChose.getSelectedFile();
	                //This is where a real application would open the file.
	                path=file.getAbsolutePath();
	                System.out.println("********** "+path);
					BaseTableModel modelB;
					try {
						System.out.println("Données chargées");
						modelB = new BaseTableModel(r.getAll(path));
						BasePanel panBase=new BasePanel(modelB);
						slideContainer2.add(panBase);
						bFind.setEnabled(true);
						bsave.setEnabled(true);
						value1.setText(BaseTableModel.getSizeBase());
						value2.setText(ChangeForm.getCritere());
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						
						JOptionPane.showMessageDialog(null, "Format de données incorrectes,Veuillez choisir un autre fichier!");
						bFind.setEnabled(false);
					}
					
	            } 
				dispMotif.updateUI();
			}
		}
		
	}
	
	public class SaveActionListener implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			Object selec = e.getSource();
			if(selec.equals(bsave)){				
				int returnVal = fileChose.showSaveDialog(FindPanel.this);
	            if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File file = fileChose.getSelectedFile();
	                String topath=file.getAbsolutePath();
	                System.out.println(topath);
	                ReadWriteFile rw=new ReadWriteFile();
	                try {
	                	if(datasave==null){
	                		JOptionPane.showMessageDialog(null, "Pas de données à sauvegarder!");
	                	}else{
	                		rw.saveToFile(datasave, topath);
	                	}
						
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	                
	            }
			}
		}
	}	
	
	
	public void colorHead(JTable tab,Color c){
		JTableHeader header = tab.getTableHeader();
		header.setBackground(c);
		header.setForeground(Color.gray);
		header.setOpaque(true);
	}
	
	public void addListTableListener(final JTable tab){
		tab.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        final ListSelectionModel cellSelectionModel = tab.getSelectionModel();
        cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent e) {
            int[] selectedRow = tab.getSelectedRows();
            int[] selectedColumns = tab.getSelectedColumns();
            
            for (int i = 0; i < selectedRow.length; i++) {
              for (int j = 0; j < selectedColumns.length; j++) {
                try {
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					//System.out.println(" Format incorrect");
				}
              }
            }
            //System.out.println("Selected: " + selectedData);
          }

        });
	}
	
	
	protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = FindPanel.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            //System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

	protected JPanel createInnerPanel(String text) {
		JPanel jplPanel = new JPanel();
		JLabel jlbDisplay = new JLabel(text);
		jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
		jplPanel.setLayout(new GridLayout(1, 1));
		jplPanel.add(jlbDisplay);
		return jplPanel;
	}
	
	 public static void main(String[] args) {
		JFrame frame = new JFrame("TabbedPane Source Demo");
		frame.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		new ControlPanel();
		new ModelMotif();
		new ModelCharge();
		
		
		new ChangeForm();
		//Gui g=new Gui(c, mp,cp);
		//InterfaceEngine i=new InterfaceEngine(m,g,c,mp);
		frame.getContentPane().add(new FindPanel(),
				BorderLayout.CENTER);
		frame.pack();
		frame.setSize(1050,600);
		frame.setVisible(true);
	}


}
